import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:lcapp/api/interface/login_api.dart';
import 'package:lcapp/api/interface/user_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/local_info.dart';
import 'package:lcapp/basic/user_info.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/data/media_asset_data_entity.dart';
import 'package:lcapp/model/dialog/confirm.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/level_picker/level_picker.dart';
import 'package:lcapp/model/oss/oss.dart';
import 'package:lcapp/model/oss/oss_util.dart';
import 'package:lcapp/model/permission/permission_operate.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/page/drawer_page.dart';
import 'package:lcapp/page/home/home_sel_address.dart';
import 'package:lcapp/widget/asr_app_bar.dart';
import 'package:lcapp/widget/asr_cache_image.dart';

class MinEditInfoPage extends StatefulWidget {
  const MinEditInfoPage({Key? key}) : super(key: key);

  @override
  _MinEditInfoPageState createState() => _MinEditInfoPageState();
}

class _MinEditInfoPageState extends State<MinEditInfoPage> {

  TextEditingController namecontroller = TextEditingController();
  TextEditingController descontroller = TextEditingController();
  TextEditingController companycontroller = TextEditingController();
  List<MediaAssetDataEntity> assets = [];
  String selSex='';
  List<String> plList = ['男','女'];
  late StreamSubscription _subscription;
  bool myState = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    myState = AsrLocalInfo.getMyState();
    refreshUserInfo(refreshBlock: (){
      setState(() {});
    });
    _subscription = eventBus.on<OssUploadState>().listen((event) {
      if (event.state == 1) {
        didSave();
      }
    });
    namecontroller.text = userInfo.name!;
    descontroller.text = userInfo.profiles!;
    companycontroller.text = userInfo.company!;
    selSex = userInfo.sex!=1?'男':'女';
  }

  @override
  void dispose() {
    super.dispose();
    _subscription.cancel();
  }

  getImage(){
    // getAlbumPermission(context, ()async{
    //   List<MediaAssetDataEntity> res = await AsrMediaPicker.pickImg(
    //     showCamera: true,selectCount: 1);
    //   if(res!=null){
    //     assets.clear();
    //     setState(() {
    //       assets.addAll(res);
    //     });
    //   }
    // });
  }

  didSave()async{

    RegExp exp = RegExp(
        r'((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}');
    RegExpMatch? matchs = exp.firstMatch(descontroller.text);
    if(matchs!=null){
      showToast('请不要输入手机号登敏感信息!');
      return;
    }


    Map<String,dynamic> info = {
      "id":userInfo.id,
      "img":assets.isNotEmpty? assets[0].url:userInfo.img,
      "name":namecontroller.text.trim(),
      "profiles":descontroller.text.trim(),
      "address":userInfo.addressRegin??'',
      "company":companycontroller.text.trim(),
      "sex":selSex=='男'?0:1,
    };
    showLoading();
    ResponseData res = await UserAPI.editMinInfo(info);
    hideLoading();
    if(res.code==200){
      showToast('保存成功~');
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bgColor,
      appBar: AsrAppBar(
        titleText: '编辑资料',
        backgroundColor: defaultBarColor,
        barColor: Colors.white,
      ),
      body: GestureDetector(
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 30.w),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  height: 150.w,
                  child: Column(
                    children: [
                      Expanded(child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text('头像',style: TextStyle(
                            color: Colors.black,
                            fontSize: 32.sp,
                          ),),
                          GestureDetector(
                            onTap: (){
                              FocusScope.of(context).requestFocus(FocusNode());
                              getImage();
                            },
                            child: Container(
                              height: 120.w,
                              width: 120.w,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(120.w)
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(100.w),
                                child: ASRCacheImage(image:assets!.isNotEmpty?assets![0].uri!:userInfo.img ?? 'assets/icon/p_head.png',width: 100.w,height: 100.w,fit: BoxFit.fitWidth,),
                              ),
                            ),
                          )
                        ],
                      )),
                      Container(
                        height: 1,
                        color: Color(0xffE9E8E9),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 100.w,
                  child: Column(
                    children: [
                      Expanded(child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text('名称',style: TextStyle(
                            color: Colors.black,
                            fontSize: 32.sp,
                          ),),
                          Container(
                            height: 120.w,
                            width: 0.7.sw,
                            child: TextField(
                              controller: namecontroller,
                              textInputAction: TextInputAction.done,
                              maxLines: 1,
                              maxLength: 5,
                              textAlign: TextAlign.right,
                              style:  TextStyle(
                                color: const Color(0xff666666),
                                fontSize: 28.sp,
                              ),
                              decoration:  InputDecoration(
                                contentPadding: EdgeInsets.only(left: 17.w),
                                hintText: "请输入名称",
                                hintStyle: TextStyle(
                                  color: const Color(0xFFAEAEAE),
                                  fontSize: 28.sp,
                                  fontWeight: FontWeight.w500,
                                ),
                                counterText: "",
                                border: const OutlineInputBorder(
                                  borderSide: BorderSide.none,
                                ),
                                fillColor: Colors.transparent,
                                filled: true,
                              ),
                            ),
                          )
                        ],
                      )),
                      Container(
                        height: 1,
                        color: Color(0xffE9E8E9),
                      )
                    ],
                  ),
                ),
                Container(
                  width: 1.sw,
                  constraints: BoxConstraints(
                    minHeight: 100.w,
                  ),
                  // height: 100.w,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text('介绍',style: TextStyle(
                              color: Colors.black,
                              fontSize: 32.sp,
                            ),),
                            Expanded(child: GestureDetector(
                              onTap: (){
                                FocusScope.of(context).requestFocus(FocusNode());
                              },
                              child: Container(
                                margin: EdgeInsets.only(left: 30.w,right: 6.w,top: 20.w,bottom: 20.w),
                                child: TextField(
                                  controller: descontroller,
                                  keyboardType: TextInputType.multiline,
                                  maxLines: null,
                                  maxLength: 30,
                                  textAlign: TextAlign.right,
                                  style:  TextStyle(
                                    color: const Color(0xff666666),
                                    fontSize: 28.sp,
                                  ),
                                  decoration:  InputDecoration(
                                    contentPadding: EdgeInsets.only(left: 17.w),
                                    hintText: "请输入介绍",
                                    hintStyle: TextStyle(
                                      color: const Color(0xFFAEAEAE),
                                      fontSize: 28.sp,
                                      fontWeight: FontWeight.w500,
                                    ),
                                    counterText: "",
                                    border: const OutlineInputBorder(
                                      borderSide: BorderSide.none,
                                    ),
                                    fillColor: Colors.transparent,
                                    filled: true,
                                  ),
                                ),
                              ),
                            )
                            ),
                          ],
                        ),
                      ),
                      Container(
                        height: 1,
                        color: Color(0xffE9E8E9),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 100.w,
                  child: Column(
                    children: [
                      Expanded(child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text('性别',style: TextStyle(
                            color: Colors.black,
                            fontSize: 32.sp,
                          ),),
                          Expanded(child: GestureDetector(
                            onTap: (){
                              FocusScope.of(context).requestFocus(FocusNode());
                              JhPickerTool.showStringPicker(
                                context,
                                title: '请选择性别',
                                data: plList,
                                clickCallBack: _selectPLSex,
                                // pickerType: AsrPickerType.PICKERORANGETHEME,
                              );
                            },
                            child: Container(
                              margin: EdgeInsets.only(left: 20.w,right: 6.w),
                              child: Text(selSex,
                                textAlign: TextAlign.right,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 28.sp,
                                ),),
                            ),
                          )),
                          Icon(Icons.arrow_forward_ios,color: Colors.black,size: 30.w,)
                        ],
                      )),
                      Container(
                        height: 1,
                        color: Color(0xffE9E8E9),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 100.w,
                  child: Column(
                    children: [
                      Expanded(child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text('实名认证',style: TextStyle(
                            color: Colors.black,
                            fontSize: 32.sp,
                          ),),
                          Expanded(child: GestureDetector(
                            onTap: (){
                              FocusScope.of(context).requestFocus(FocusNode());
                              if(userInfo.card!=1){
                                Navigator.of(context).pushNamed('MInSmrzPage').then((value){
                                  refreshUserInfo(refreshBlock: (){
                                    setState(() {});
                                  });
                                });
                              }else{
                                Navigator.of(context).pushNamed('MInSmrzDetailPage').then((value){
                                  refreshUserInfo(refreshBlock: (){
                                    setState(() {});
                                  });
                                });
                              }
                            },
                            child: Container(
                              margin: EdgeInsets.only(left: 20.w,right: 6.w),
                              child: Text(userInfo.realName ?? '去认证',
                                textAlign: TextAlign.right,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 28.sp,
                                ),),
                            ),
                          )),
                          Icon(Icons.arrow_forward_ios,color: Colors.black,size: 30.w,)
                        ],
                      )),
                      Container(
                        height: 1,
                        color: Color(0xffE9E8E9),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 120.w,
                  child: Column(
                    children: [
                      Expanded(child: GestureDetector(
                        onTap: (){
                          FocusScope.of(context).requestFocus(FocusNode());
                          Navigator.of(context).pushNamed('MinAddressListPage').then((value){
                            refreshUserInfo(refreshBlock: (){
                              setState(() {
                              });
                            });
                          });
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Text('经营地址',style: TextStyle(
                              color: Colors.black,
                              fontSize: 32.sp,
                            ),),
                            Expanded(child: GestureDetector(
                              onTap: (){
                                FocusScope.of(context).requestFocus(FocusNode());
                                Navigator.of(context).pushNamed('MinAddressListPage').then((value){
                                  refreshUserInfo(refreshBlock: (){
                                    setState(() {
                                    });
                                  });
                                });
                              },
                              child: Container(
                                color: Colors.transparent,
                                margin: EdgeInsets.only(left: 20.w,right: 6.w),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: [
                                    Text(userInfo.addressRegin??'',
                                      textAlign: TextAlign.right,
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 28.sp,
                                      ),),
                                    SizedBox(height: 4.w,),
                                    Text(userInfo.addressDetail??'',
                                      textAlign: TextAlign.right,
                                      style: TextStyle(
                                        color: Color(0XFF666666),
                                        fontSize: 28.sp,
                                      ),)
                                  ],
                                ),
                              ),
                            )),
                            Icon(Icons.arrow_forward_ios,color: Colors.black,size: 30.w,)
                          ],
                        ),
                      )
                      ),
                      Container(
                        height: 1,
                        color: Color(0xffE9E8E9),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 100.w,
                  child: Column(
                    children: [
                      Expanded(child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Expanded(child: Text('个性化推荐',style: TextStyle(
                            color: Colors.black,
                            fontSize: 32.sp,
                          ),)),
                          Container(
                              margin:
                              EdgeInsets.only(right: 0.w),
                              child: FlutterSwitch(
                                width: 100.w,
                                height: 60.w,
                                value: myState,
                                activeColor: Colors.green,
                                borderRadius: 30.0,
                                onToggle: (value) {
                                  setState(() {
                                    AsrLocalInfo.setMyState(value);
                                    myState = value;
                                  });
                                  if (value == false) {
                                    showToast('已为您关闭个性化推荐功能~');
                                  }
                                },
                              ))
                        ],
                      )),
                      Container(
                        height: 1,
                        color: Color(0xffE9E8E9),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 100.w,
                  child: Column(
                    children: [
                      Expanded(child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Expanded(child: Text('注销账号',style: TextStyle(
                            color: Colors.black,
                            fontSize: 32.sp,
                          ),)),
                          GestureDetector(
                            onTap: (){
                              FocusScope.of(context).requestFocus(FocusNode());
                              openConfirm(
                                context,
                                isTitle: true,
                                title: '注销账号',
                                content: '注销账号后您在本平台的相关数据将被删除，无法找回',
                                succFn: () async{
                                  ResponseData res = await LoginAPI.cancleAccount();
                                  if(res.code==200){
                                    clearUserInfo();
                                    eventBus.fire(HomeToIndex(index: 0));
                                    Navigator.pushAndRemoveUntil(context, PageRouteBuilder(
                                        settings: RouteSettings(name: "index"),
                                        pageBuilder:
                                            (BuildContext context, Animation animation,
                                            Animation secondaryAnimation) {
                                          return DrawerPage();
                                        }), (route) => false);
                                  }
                                },
                              );
                            },
                            child: Container(
                              padding: EdgeInsets.symmetric(vertical: 6.w,horizontal: 16.w),
                              decoration: BoxDecoration(
                                  color: defaultBarColor,
                                  borderRadius: BorderRadius.circular(20.w)
                              ),
                              margin: EdgeInsets.only(left: 20.w,right: 6.w),
                              child: Text('申请注销',
                                textAlign: TextAlign.right,
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 28.sp,
                                ),),
                            ),
                          )
                        ],
                      )),
                      Container(
                        height: 1,
                        color: Color(0xffE9E8E9),
                      )
                    ],
                  ),
                ),
                // Container(
                //   height: 100.w,
                //   child: Column(
                //     children: [
                //       Expanded(child: Row(
                //         mainAxisAlignment: MainAxisAlignment.start,
                //         children: [
                //           Text('企业名称',style: TextStyle(
                //             color: Colors.black,
                //             fontSize: 32.sp,
                //           ),),
                //           Expanded(child: GestureDetector(
                //             onTap: (){
                //               FocusScope.of(context).requestFocus(FocusNode());
                //             },
                //             child: Container(
                //               margin: EdgeInsets.only(left: 20.w,right: 6.w),
                //               child: TextField(
                //                 controller: companycontroller,
                //                 textInputAction: TextInputAction.done,
                //                 maxLines: 1,
                //                 maxLength: 20,
                //                 textAlign: TextAlign.right,
                //                 style:  TextStyle(
                //                   color: const Color(0xff666666),
                //                   fontSize: 28.sp,
                //                 ),
                //                 decoration:  InputDecoration(
                //                   contentPadding: EdgeInsets.only(left: 17.w),
                //                   hintText: "请输入企业名称",
                //                   hintStyle: TextStyle(
                //                     color: const Color(0xFFAEAEAE),
                //                     fontSize: 28.sp,
                //                     fontWeight: FontWeight.w500,
                //                   ),
                //                   counterText: "",
                //                   border: const OutlineInputBorder(
                //                     borderSide: BorderSide.none,
                //                   ),
                //                   fillColor: Colors.transparent,
                //                   filled: true,
                //                 ),
                //               ),
                //             ),
                //           )),
                //         ],
                //       )),
                //       Container(
                //         height: 1,
                //         color: Color(0xffE9E8E9),
                //       )
                //     ],
                //   ),
                // ),
                Container(
                  margin: EdgeInsets.only(top: 65.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        height: 2,
                        width: 150.w,
                        color: Color(0xffE9E8E9),
                      ),
                      SizedBox(width: 30.w,),
                      Container(
                        child: Text('粮策号: ',style: TextStyle(
                          color: Colors.black,
                          fontSize: 40.sp,
                          fontWeight: FontWeight.w600
                        ),),
                      ),
                      Container(
                        child: Text(userInfo.grainid??'',style: TextStyle(
                            color: Color(0xffEB712E),
                            fontSize: 40.sp,
                            fontWeight: FontWeight.w600
                        ),),
                      ),
                      SizedBox(width: 30.w,),
                      Container(
                        height: 2,
                        width: 150.w,
                        color: Color(0xffE9E8E9),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 65.w),
                  child: GestureDetector(
                    onTap: (){
                      FocusScope.of(context).requestFocus(FocusNode());
                      if(assets.isNotEmpty){
                        // AsrOss.ossUploadVideo(assets);
                      }else{
                        didSave();
                      }

                    },
                    child: Stack(
                      children: [
                        Image.asset('assets/min/min_bc_btn.png',width: 1.sw-60.w,),
                        Center(child: Container(
                          height: 100.w,
                          alignment: Alignment.center,
                          child: Text('保存',style: TextStyle(
                              color: Colors.white,
                              fontSize: 40.sp,
                              fontWeight: FontWeight.w500
                          ),),
                        ),)
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  _selectPLSex(int index, dynamic selectDate) {
    setState(() {
      selSex = selectDate;
    });
  }

}
